package yunhe.servlet;

import yunhe.entity.AdminInfo;
import yunhe.entity.BoardInfo;
import yunhe.entity.NewsInfo;
import yunhe.service.NewsServers;
import yunhe.service.impl.NewsServersImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@SuppressWarnings("serial")
public class AddNews extends HttpServlet {
	
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String title=req.getParameter("title");
		String context=req.getParameter("context");
		HttpSession session=req.getSession();
		AdminInfo admin=(AdminInfo)session.getAttribute("adminInfo");
		int optionId =Integer.parseInt(req.getParameter("board"));
		BoardInfo board=((List<BoardInfo>)session.getAttribute("boards")).get(optionId);
		
		NewsInfo ni=new NewsInfo();
		ni.setTitle(title);
		ni.setContext(context); 
		ni.setAdmin(admin);
		ni.setBoard(board);
		
		String clickedId=req.getParameter("clickedId");
		if(clickedId!=null){
			int nId=((List<NewsInfo>)session.getAttribute("news")).get(Integer.parseInt(clickedId)).getnId();
			ni.setnId(nId);
		}				
		NewsServers ns=new NewsServersImpl();
		int re;
		if(clickedId!=null){  //clickedId不为null的时候，说明是修改
			re=ns.updateNews(ni);
		}
		else{
			re=ns.addNews(ni);
		}
		if(re>0){
			session.setAttribute("addNewsSucc", true);
		}
		else{
			session.setAttribute("addNewsSucc", false);
		}
		resp.sendRedirect("addnews.jsp");
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}
